package org.hong.monkey

import java.io.File

import com.google.common.io.Files
import org.hong.monkey.util.Utils

/**
 */
private[monkey] class HttpFileServer(conf: MonkeyConf, requestedPort: Int = 0) extends Logging {

  var baseDir : File = null
  var fileDir : File = null
  var jarDir : File = null
  var httpServer : HttpServer = null
  var serverUri : String = null

  def initialize() {
    baseDir = Utils.createTempDir(Utils.getLocalDir(conf), "httpd")
    fileDir = new File(baseDir, "files")
    jarDir = new File(baseDir, "jars")
    fileDir.mkdir()
    jarDir.mkdir()
    logInfo("HTTP File server directory is " + baseDir)
    httpServer = new HttpServer(conf, baseDir, requestedPort, "HTTP file server")
    httpServer.start()
    serverUri = httpServer.uri
    logDebug("HTTP file server started at: " + serverUri)
  }

  def stop() {
    httpServer.stop()

    // If we only stop sc, but the driver process still run as a services then we need to delete
    // the tmp dir, if not, it will create too many tmp dirs
    try {
      Utils.deleteRecursively(baseDir)
    } catch {
      case e: Exception =>
        logWarning(s"Exception while deleting Monkey temp dir: ${baseDir.getAbsolutePath}", e)
    }
  }

  def addFile(file: File) : String = {
    addFileToDir(file, fileDir)
    serverUri + "/files/" + Utils.encodeFileNameToURIRawPath(file.getName)
  }

  def addJar(file: File) : String = {
    addFileToDir(file, jarDir)
    serverUri + "/jars/" + Utils.encodeFileNameToURIRawPath(file.getName)
  }

  def addFileToDir(file: File, dir: File) : String = {
    if (file.isDirectory) {
      throw new IllegalArgumentException(s"$file cannot be a directory.")
    }
    Files.copy(file, new File(dir, file.getName))
    dir + "/" + Utils.encodeFileNameToURIRawPath(file.getName)
  }

}
